package com.zfl.init;

import com.zfl.entity.RolePermission;
import com.zfl.mapper.RolePermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.boot.CommandLineRunner;

import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class RolePermInitRunner implements CommandLineRunner {

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /** Redis中存储角色权限的Key前缀 */
    private static final String ROLE_PERM_BIT_KEY_PREFIX = "role:perm:bit:";

    @Override
    public void run(String... args) throws Exception {
        log.info("=== 开始加载角色权限位到Redis ===");


        // 步骤1：先删除Redis中旧的角色权限数据（所有以ROLE_PERM_BIT_KEY_PREFIX开头的键）
        // 注意：生产环境中若数据量大，建议用scan命令替代keys（避免阻塞Redis）
        Set<String> oldKeys = redisTemplate.keys(ROLE_PERM_BIT_KEY_PREFIX + "*");
        if (oldKeys != null && !oldKeys.isEmpty()) {
            redisTemplate.delete(oldKeys);
            log.info("已清除Redis中旧的角色权限数据，共{}条", oldKeys.size());
        }

        // 2. 查询所有角色-权限位总和的配置
        List<RolePermission> rolePerms = rolePermissionMapper.selectAll();
        if (rolePerms.isEmpty()) {
            log.warn("数据库中未找到角色-权限配置，权限加载终止");
            return;
        }

        // 3. 遍历并存入Redis
        for (RolePermission rolePerm : rolePerms) {
            Long roleId = rolePerm.getRoleId();
            Integer permBitSum = rolePerm.getPermBitSum();

            String redisKey = ROLE_PERM_BIT_KEY_PREFIX + roleId;
            redisTemplate.opsForValue().set(redisKey, permBitSum);

            log.info("角色ID={} 的权限位总和={} 已成功加载到Redis（Key={}）",
                    roleId, permBitSum, redisKey);
        }

        log.info("=== 角色权限位加载到Redis完成（共加载{}条记录）===", rolePerms.size());
    }
}